﻿///////////////////////////////////////////////////////////////////////////////
// File:        ConnectionOutputStream.cc
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#include "nio/net/ConnectionOutputStream.hpp"
using namespace nio::net;

#define SEND_BUFF_SIZE  0x4000

ConnectionOutputStream::ConnectionOutputStream(Socket& sock, unsigned int size)
    : ConnectionStream(sock, size)
    , sendBytsFN_()
{

}

ConnectionOutputStream::ConnectionOutputStream(Socket& sock, ByteBuffer buff, unsigned int size)
    : ConnectionStream(sock, buff, size)
    , sendBytsFN_()
{

}

ConnectionOutputStream::~ConnectionOutputStream()
{

}

int ConnectionOutputStream::flush()
{
    if (size() <= 0)
        return 0;

    unsigned int bytsTransfered = 0;
    char sendBuf[SEND_BUFF_SIZE];

    while (size() > 0)
    {
        unsigned int bytsRead = peek(sendBuf, SEND_BUFF_SIZE);
        while (bytsRead > 0)
        {
            int bytsSend = sock_.write(sendBuf, bytsRead);
            if (bytsSend < 0)
            {
                if (bytsSend == SOCKET_ERROR_WOULDBLOCK)
                    return bytsTransfered;
                else
                    return SOCKET_ERROR;
            }

            bytsTransfered += (unsigned int)bytsSend;

            bytsRead -= (unsigned int)bytsSend;
            skip((unsigned int)bytsSend);
        }
    }

    sendBytsFN_(bytsTransfered);
    return bytsTransfered;
}


